#include "preHeader.h"
#include "CreatureLooterMgr.h"
#include "Map/MapInstance.h"

#define ActiveLooterDistMax (30.f*30.f)

CreatureLooterMgr::CreatureLooterMgr(Creature* pCreature)
: m_pCreature(pCreature)
{
}

CreatureLooterMgr::~CreatureLooterMgr()
{
}

void CreatureLooterMgr::AddPlayer(Player* pPlayer, uint64 damage)
{
	m_allLooters[pPlayer->GetGuid()].totalDamage += damage;
}

Player* CreatureLooterMgr::CalcFinalLooter() const
{
	struct ActiveLooter {
		Player* pPlayer;
		uint64 totalDamage;
	};
	std::vector<ActiveLooter> activeLooters;
	activeLooters.reserve(m_allLooters.size());

	auto pMapInstance = m_pCreature->GetMapInstance();
	for (auto&[guid, looter] : m_allLooters) {
		auto pPlayer = pMapInstance->GetPlayer(guid);
		if (pPlayer == NULL) {
			continue;
		}
		if (pPlayer->GetDistanceSq(m_pCreature) > ActiveLooterDistMax) {
			continue;
		}
		activeLooters.push_back({pPlayer, looter.totalDamage});
	}
	if (activeLooters.empty()) {
		return NULL;
	}

	auto sltIdx = RandomByWeightValue<s64>(activeLooters.data(),
		activeLooters.size(), [](const ActiveLooter& looter) {
		return (s64)looter.totalDamage;
	});
	return activeLooters[sltIdx].pPlayer;
}
